package com.hsy.order.utils

import android.content.Context
import com.flux.utils.BaseFileUtil
import java.io.*


/**
 * Created on 2018/2/1.
 *
 * @author Yang
 */
object FileUtil {

    private val DIR_IMAGE = File.separator + "image" + File.separator
    private const val M = 1024 * 1024

    /**
     * 获取缓存文件大小
     */
    fun getCacheSize(context: Context): String {
        val cache = BaseFileUtil.getCacheDir(context)
        val size: Long = getDirSize(cache)
        return when (size) {
            0L -> "无缓存"
            in 1..M -> "不足1M"
            else -> "${size / M}M"
        }
    }

    private fun getDirSize(dir: File): Long {
        var size: Long = 0
        for (file in dir.listFiles()) {
            size = if (file.isDirectory) {
                size + getDirSize(file)
            } else {
                size + file.length()
            }
        }
        return size
    }

    /**
     * 清空缓存文件
     */
    fun clearCache(context: Context) {
        val cacheDir = BaseFileUtil.getCacheDir(context)
        BaseFileUtil.emptyDir(cacheDir)
    }


    /**
     * 生成图片缓存文件
     *
     * @param context
     * @param prefix
     * @return
     */
    fun getImageCacheFile(context: Context, ext: String, vararg prefix: String): File {
        val p = if (prefix.isNotEmpty()) prefix[0] + "_" else ""
        val imageCacheDir = getImageCacheDir(context)
        return File(imageCacheDir.absolutePath + File.separator + p + System.currentTimeMillis() + ext)
    }

    /**
     * 获取图片缓存文件夹
     *
     * @param context
     * @return
     */
    fun getImageCacheDir(context: Context): File {
        val cacheDir = BaseFileUtil.getCacheDir(context)
        val imageCacheDir = File(cacheDir.absolutePath + DIR_IMAGE)
        if (!imageCacheDir.exists()) {
            imageCacheDir.mkdirs()
        }
        return imageCacheDir
    }
}